<template>
  <div class="app-container">
    <el-button type="primary" @click="handleAddAdmin">添加员工</el-button>

    <el-table :data="adminList" height="550" style="width: 100%;margin-top:30px;" stripe>
      <el-table-column 
        align="center" 
        label="头像">
        <template slot-scope="scope">
          <img :src="scope.row.avatar" style="width: 100px; height: 100px" class="user-avatar">
        </template>
      </el-table-column>
      <el-table-column 
        prop="nickName" 
        align="center" 
        label="昵称">
      </el-table-column>
      <el-table-column 
        prop="code" 

        align="center" 
        label="工号">
      </el-table-column>
      <el-table-column 
        prop="trueName" 
        align="center" 
        label="姓名">
      </el-table-column>
      <el-table-column 
        prop="phone" 
        align="center" 
        label="电话">
      </el-table-column>
      <el-table-column 
        prop="email" 
        align="center" 
        label="邮箱">
      </el-table-column>
      <el-table-column 
        prop="gender" 
        align="center" 
        label="性别">
      </el-table-column>
      <el-table-column 
        prop="birthday" 
        align="center" 
        label="生日">
      </el-table-column>
      <el-table-column 
        prop="status" 
        align="center" 
        label="状态">
      </el-table-column>
      <el-table-column 
        prop="createAt" 
        align="center" 
        label="创建时间">
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleRole(scope)">分配角色</el-button>
          <el-button type="text" size="small" @click="handleStatus(scope)">启用/禁用</el-button>
          <el-button type="text" size="small" @click="handleEdit(scope)">编辑</el-button>
          <el-button type="text" size="small" @click="handleDetail(scope)">详情</el-button>
          <el-button type="text" size="small" @click="handleDelete(scope)">删除</el-button>
        </template>
      </el-table-column>


    </el-table>

    <!-- 分页 -->
    <div class="block">
        <span class="demonstration"></span>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total">
        </el-pagination>
    </div>


    <!-- 新增用户 -->
    <el-dialog :visible.sync="addAdminDialogVisible" title="添加员工">
      <el-form ref="createAdminForm" :model="createAdminForm" label-width="80px" label-position="left">
        <!-- 头像 -->
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:9527/aliyun/oss/upload"
            :headers="headers"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="createAdminForm.avatar" :src="createAdminForm.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="用户名">
          <el-input v-model="createAdminForm.username" placeholder="用户名" />
        </el-form-item>

        <el-form-item label="密码">
          <el-input v-model="createAdminForm.password" placeholder="密码" />
        </el-form-item>

        <el-form-item label="确认密码">
          <el-input v-model="createAdminForm.cpassword" placeholder="确认密码" />
        </el-form-item>

        <el-form-item label="昵称">
          <el-input v-model="createAdminForm.nickName" placeholder="昵称" />
        </el-form-item>

        <el-form-item label="真实姓名">
          <el-input v-model="createAdminForm.trueName" placeholder="真实姓名" />
        </el-form-item>

        <el-form-item label="联系方式">
          <el-input v-model="createAdminForm.phone" placeholder="联系方式" />
        </el-form-item>

        <el-form-item label="邮箱">
          <el-input v-model="createAdminForm.email" placeholder="邮箱" />
        </el-form-item>

        <el-form-item label="性别">
            <el-radio v-model="createAdminForm.gender" label="1">男</el-radio>
            <el-radio v-model="createAdminForm.gender" label="2">女</el-radio>
        </el-form-item>

        <el-form-item label="生日">
          <el-date-picker
            v-model="createAdminForm.birthday"
            type="date"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>

      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="addAdminDialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmAdd">确认</el-button>
      </div>
    </el-dialog>

    <!-- 分配角色 -->
    <el-dialog :visible.sync="roleDialogVisible" title="分配角色">
      <el-form :model="updateRoleForm" label-width="80px" label-position="left">
        <el-form-item label="昵称">
          <el-input v-model="updateRoleForm.nickName" placeholder="昵称" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="updateRoleForm.roleIds" multiple placeholder="请选择">
            <el-option
              v-for="item in roles"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="roleDialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmRole">确认</el-button>
      </div>
    </el-dialog>

    <!-- 员工详情 -->
    <el-dialog :visible.sync="detailDialogVisible" title="员工详情">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>基本信息</span>
        </div>
        <div class="text item">
          <el-row>
            <el-col :span="6"><div class="grid-content">头像：<img :src="adminDetail.admin.avatar" style="width: 100px; height: 100px" class="user-avatar"></div></el-col>
            <el-col :span="6"><div class="grid-content"></div></el-col>
            <el-col :span="6"><div class="grid-content"></div></el-col>
            <el-col :span="6"><div class="grid-content"></div></el-col>
          </el-row>
          <el-row>
            <el-col :span="10"><div class="grid-content">工号：{{ adminDetail.admin.code }}</div></el-col>
            <el-col :span="10"><div class="grid-content">昵称：{{ adminDetail.admin.nickName }}</div></el-col>
          </el-row>
          <el-row>
            <el-col :span="10"><div class="grid-content">姓名：{{ adminDetail.admin.trueName }}</div></el-col>
            <el-col :span="10"><div class="grid-content">电话：{{ adminDetail.admin.phone }}</div></el-col>

          </el-row>
          <el-row>
            <el-col :span="10"><div class="grid-content">生日：{{ adminDetail.admin.birthday }}</div></el-col>
            <el-col :span="10"><div class="grid-content">性别：{{ adminDetail.admin.gender }}</div></el-col>
          </el-row>
          <el-row>
            <el-col :span="10"><div class="grid-content">邮箱：{{ adminDetail.admin.email }}</div></el-col>
            <el-col :span="10"><div class="grid-content">状态：{{ adminDetail.admin.status }}</div></el-col>
          </el-row>
        </div>
      </el-card>

      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>角色</span>
        </div>
        <div class="text item">
          <el-row>
            <el-col :span="20"><div class="grid-content"><el-tag v-for="role in adminDetail.roles" :key="role.name">{{ role.name }}</el-tag></div></el-col>
          </el-row>
        </div>
      </el-card>

      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>菜单权限</span>
        </div>
        <div class="text item">
          <el-row>
            <el-col :span="20"><div class="grid-content"><el-tag v-for="menu in adminDetail.menuVOS" :key="menu.title">{{ menu.title }}</el-tag></div></el-col>
          </el-row>
        </div>
      </el-card>

      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>资源权限</span>
        </div>
        <div class="text item">
          <el-row>
            <el-col :span="20"><div class="grid-content"><el-tag v-for="resource in adminDetail.resourceVOS" :key="resource.name">{{ resource.name }}</el-tag></div></el-col>
          </el-row>
        </div>
      </el-card>
    </el-dialog>
  </div>
</template>

<script>
import path from 'path'
import { deepClone } from '@/utils'
import store from '@/store'
import { getToken } from '@/utils/auth'
import { getRoles, getRoleByAdmin } from '@/api/role'
import { getAdminList, addAdmin, updateAdmin, updateStatus, getAdminDetail, delAdmin, updateRole, uploadAvatar } from '@/api/user'

const defaultRole = {
  key: '',
  name: '',
  description: '',
  routes: []
}

export default {
  data() {
    return {
      createAdminForm: {
        avatar: '',
        username: '',
        password: '',
        cpassword: '',
        email: '',
        nickName: '',
        trueName: '',
        phone: '',
        gender: '',
        birthday: ''
      },
      updateRoleForm: {
        adminId: '',
        nickName: '',
        roleIds: []
      },
      roles: [],
      adminDetail: {
        admin: {},
        roles: [],
        menuVOS: [],
        resourceVOS: []
      },
      routes: [],
      adminList: [
      //   {
      //   avatar: '1',
      //   nickName: '小凡',
      //   code: 'A0001',
      //   trueName: '陈洪裕',
      //   phone: '14718120240',
      //   email: '1325852113@qq.com',
      //   gender: '男',
      //   birthday: '1999-06-05',
      //   status: '启用',
      //   createAt: '2021-02-19'
      // }
      ],
      addAdminDialogVisible: false,
      roleDialogVisible: false,
      detailDialogVisible: false,
      dialogType: 'new',
      imageUrl: '',
      headers: {
        Authorization: ''
      },
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      page: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      }
    }
  },
  computed: {
    routesData() {
      return this.routes
    }
  },
  created() {
    // Mock: get all routes and roles list from server
    this.getAdminList()
    this.getRoles()
    this.setToken()
  },
  
  methods: {
    async getAdminList() {
      const res = await getAdminList(this.page)
      console.log(res)
      this.page.total = res.data.adminNum
      this.adminList = res.data.admins
    },
    async getRoles() {
      const res = await getRoles()
      console.log(res)
      this.roles = res.data
    },
    setToken() {
      console.log("token",getToken())
      if (store.getters.token) {
        this.headers.Authorization = getToken()
      }
      // console.log("token",headers)
    },

    // Reshape the routes structure so that it looks the same as the sidebar
    generateRoutes(routes, basePath = '/') {
      const res = []

      for (let route of routes) {
        // skip some route
        if (route.hidden) { continue }

        const onlyOneShowingChild = this.onlyOneShowingChild(route.children, route)

        if (route.children && onlyOneShowingChild && !route.alwaysShow) {
          route = onlyOneShowingChild
        }

        const data = {
          path: path.resolve(basePath, route.path),
          title: route.meta && route.meta.title

        }

        // recursive child routes
        if (route.children) {
          data.children = this.generateRoutes(route.children, data.path)
        }
        res.push(data)
      }
      return res
    },
    generateArr(routes) {
      let data = []
      routes.forEach(route => {
        data.push(route)
        if (route.children) {
          const temp = this.generateArr(route.children)
          if (temp.length > 0) {
            data = [...data, ...temp]
          }
        }
      })
      return data
    },
    handleAddAdmin() {
      // this.createAdminForm = {}
      // this.dialogType = 'new'
      this.addAdminDialogVisible = true
    },
    handleEdit(scope) {
      // const { } = scope.row
      this.dialogType = 'edit'
      this.addAdminDialogVisible = true
    },
    async handleRole(scope) {
      //获取当前用户已有角色
      const  curAdminRoles = await getRoleByAdmin(scope.row.id)
      console.log("curAdminRoles",curAdminRoles)
      const roleIds =  curAdminRoles.data.filter(item => item.id)
      console.log("roleIds",roleIds)
      this.updateRoleForm.roleIds = roleIds

      this.updateRoleForm.adminId = scope.row.id
      this.updateRoleForm.nickName = scope.row.nickName

      console.log("updateRoleForm",this.updateRoleForm)
      this.roleDialogVisible = true
    },
    handleStatus(scope) {
      const admin = scope.row
      const status = admin.status == '启用' ? '禁用' : '启用'
      this.$confirm('确认'+status+admin.nickName+'?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          if(status === '启用'){
            await updateStatus(admin.id,1)
          }else{
            await updateStatus(admin.id,0)
          }
          this.$message({
            type: 'success',
            message: '更新员工状态成功'
          })
          this.getAdminList()
        })
        .catch(err => { console.error(err) })
    },
    async handleDetail(scope) {
      const res = await getAdminDetail(scope.row.id)
      console.log("Admin Detail", res)
      this.adminDetail = res.data
      this.detailDialogVisible = true

    },
    handleDelete(scope) {
      this.$confirm('确认删除员工'+scope.row.nickName+'?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await delAdmin(scope.row.id)
          this.$message({
            type: 'success',
            message: '删除成功'
          })
          this.getAdminList()
        })
        .catch(err => { console.error(err) })
    },
    handelUpload(file) {
      console.log("uplaod file",file.file)
      uploadAvatar(file.file).then(res => {
        console.log("uplaod res",res.data)
        this.createAdminForm.avatar = res.data.url
        this.$message({
          type: 'success',
          message: '删除成功'
        })
      })

    },
    generateTree(routes, basePath = '/', checkedKeys) {
      const res = []

      for (const route of routes) {
        const routePath = path.resolve(basePath, route.path)

        // recursive child routes
        if (route.children) {
          route.children = this.generateTree(route.children, routePath, checkedKeys)
        }

        if (checkedKeys.includes(routePath) || (route.children && route.children.length >= 1)) {
          res.push(route)
        }
      }
      return res
    },
    confirmRole() {
      updateRole(this.updateRoleForm).then(() => {
        this.$message({
          type: 'success',
          message: '分配角色成功'
        })
      })

      this.roleDialogVisible = false

    },
    confirmAdd() {
      // const isEdit = this.dialogType === 'edit'
      addAdmin(this.createAdminForm).then(() => {
        this.$message({
            type: 'success',
            message: '添加员工成功!'
        })
      }).catch(() => {
        this.$message.error('添加失败');
      })

      this.addAdminDialogVisible = false
      this.getAdminList()
    },
    // reference: src/view/layout/components/Sidebar/SidebarItem.vue
    onlyOneShowingChild(children = [], parent) {
      let onlyOneChild = null
      const showingChildren = children.filter(item => !item.hidden)

      // When there is only one child route, the child route is displayed by default
      if (showingChildren.length === 1) {
        onlyOneChild = showingChildren[0]
        onlyOneChild.path = path.resolve(parent.path, onlyOneChild.path)
        return onlyOneChild
      }

      // Show parent if there are no child route to display
      if (showingChildren.length === 0) {
        onlyOneChild = { ... parent, path: '', noShowingChildren: true }
        return onlyOneChild
      }

      return false
    },
    //分页
    handleSizeChange(val) {
        this.getAdminList()
        console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
        this.getAdminList()
        console.log(`当前页: ${val}`);
    },
    //头像上传
    handleAvatarSuccess(res, file) {
        this.createAdminForm.avatar = res.data
    },
    beforeAvatarUpload(file) {
        // const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        // if (!isJPG) {
        //   this.$message.error('上传头像图片只能是 JPG 格式!');
        // }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isLt2M;
    },
    delAdmin(id) {
      console.log("id",id)
      this.$confirm('确认删除此用户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delAdmin(id)
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        this.getAdminList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    }
  }
}
</script>

<style lang="scss" scoped>
  .app-container {
    .roles-table {
      margin-top: 30px;
    }
    .permission-tree {
      margin-bottom: 30px;
    }
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
